<template>
  <fm-generate-form :data="jsonData" ref="generateForm" :value="values" :remote="remoteFuncs" insite="true" @on-change="getValue">
    <template v-for="item in blankList" :slot="item.model">
      <slot :name="item.model"></slot>
    </template>
  </fm-generate-form>
</template>
<script>
import FmGenerateForm from '../components/GenerateForm.vue'
export default {
  components: { FmGenerateForm },
  props: ['forms', 'moudleKey', 'remoteFuncs', 'values'],
  data() {
    return {
      jsonData: {
        list: [],
        config: {
          labelWidth: 100,
          labelCol: { span: 1, offset: 0 },
          wrapperCol: { span: 1, offset: 0 },
          labelPosition: 'right',
          formLayout: 'vertical',
          size: 'small'
        }
      },
      dynamicData: {},
      blankList: []
    }
  },
  watch: {
    forms(val) {
      this.formatFormData(val)
    }
  },
  created() {
    this.formatFormData(this.forms)
  },
  mounted() {},
  methods: {
    // 格式化表单数据
    formatFormData(val) {
      if (this.moudleKey === undefined && val !== null) {
        this.jsonData = val
        this.blankList = []
        this.jsonData['list'].forEach((item) => {
          if (item.type === 'blank') {
            this.blankList.push(item)
          }
        })
      } else if (val !== null && val[this.moudleKey] !== null && val[this.moudleKey].options !== '{}' && val[this.moudleKey].json !== '{}') {
        this.jsonData['config'] = JSON.parse(val[this.moudleKey].options)
        this.jsonData['list'] = JSON.parse(val[this.moudleKey].json)
        this.blankList = []
        this.jsonData['list'].forEach((item) => {
          if (item.type === 'blank') {
            this.blankList.push(item)
          }
        })
      }
    },
    getData(cb) {
      this.$refs.generateForm
        .getData()
        .then((res) => {
          cb(res, true)
        })
        .catch((e) => {
          // 数据校验失败
          cb(e, false)
        })
    },
    getValue() {
      this.$refs.generateForm
        .getData()
        .then((res) => {
          this.$emit('getValue', res)
        })
        .catch((e) => {
          // 数据校验失败
          this.$emit('getValue', e)
        })
    },
    // 设置禁用字段
    fieldsDisabled(disabledFields, filedDisable) {
      this.$refs['generateForm'].fieldsDisabled(disabledFields, filedDisable)
    },
    // 设置隐藏字段
    fieldsHidden(disabledFields, filedDisable) {
      this.$refs['generateForm'].fieldsHidden(disabledFields, filedDisable)
    },
    // 表单所有字段禁用
    fromDisabled() {
      this.$refs['generateForm'].fromDisabled()
    }
  }
}
</script>
